document.navigation = 0;
document.subjects = new Array();

if(document.getElementById('uri_target'))
	 { var url2query = document.getElementById('uri_target').value;
	 }
	 if(!url2query)
	 {
	   var url2query = 'http://ibl.mdanderson.org/TCGA/';  
	 }

    
	// var src =url2query  +"/S3QL.php?format=json&query=<S3QL><from>collections</from><where><project_id>126</project_id></where></S3QL>";
	//s3db_jsonpp_call (src,'collectionDisplay(ans)');
	 
	// var src =url2query  + "/S3QL.php?format=json&query=<S3QL><from>rules</from><where><project_id>126</project_id></where></S3QL>";
	// s3db_jsonpp_call (src,'findRules("", ans, \'where\',\'where_attr_td\')');

	
	if(document.getElementById('query') && document.getElementById('queries'))
	{document.getElementById('query').innerHTML = document.getElementById('queries').value; 
	}
	if(document.getElementById('select'))
	{
	ruleConstrain(document.getElementById('select').value, document.getElementById('select').value+'_rules','where_attr_td',1)
	}

   //As soon as the interface is ready, constrain the values in the Rules
 function documentReady() {
   
   ruleConstrain(document.getElementById('select').value, document.getElementById('select').value+'_rules','where_attr_td',1);   
 }

function get_projects(url,whereTo) {
	
    if(!url){
	var url = document.getElementById('s3db_deployment').value;
	}

    var key = document.getElementById('key');
	
		if(key)
			{user_key = key.value;
			url += "/S3QL.php?key="+user_key+"&query=<S3QL><from>projects</from><order_by>project_id</order_by></S3QL>";
			}
		else {
			url += "/S3QL.php"+"&query=<S3QL><from>projects</from><order_by>project_id</order_by></S3QL>";
		}
	  
    	s3db_jsonpp_call(url,"display_projects(ans, '','"+whereTo+"')");
    	
    	
}

function display_projects(ans,divname,whereTo) {
	
    var sel = document.createElement('select');
	var url = document.getElementById('s3db_deployment').value;
	 sel.id = "projects";
	 //sel.setAttribute("onfocus", "read_domain_into_boxes('"+url+"')");
	 sel.setAttribute("onChange", "get_collections_and_rules();");
	 if(!divname) {divname='projects_table_list';}
    
	 if(ans)
		{
		 var op = document.createElement('option');sel.appendChild(op);
		 for (var i in ans) {
			var op = document.createElement('option');
			if(ans[i].project_id){
			op.id = ans[i].project_id;
			op.value = ans[i].project_id;
			op.innerHTML = ans[i].project_name;
			sel.appendChild(op);
			}
		 }
		}
	
	div = document.getElementById(divname);
	div.innerHTML = "";
	div.appendChild(sel);
	document.getElementById('projects_table').style.display = 'inline';
	
    if(whereTo)
    {
    eval(whereTo)
    }
}

function get_collections_and_rules(url2query,project_id,key){
     
    if(!url2query) var url2query=document.getElementById('s3db_deployment').value;
    if(!project_id) var project_id=document.getElementById('projects').value;
	if(!key) 
		if(document.getElementById('key')){
		var key = document.getElementById('key').value;
		}
    
    var src =url2query  +"/S3QL.php?format=json&key="+key+"&query=<S3QL><from>collections</from><where><project_id>"+project_id+"</project_id></where></S3QL>";
    s3db_jsonpp_call (src,'collectionDisplay(ans)');
    
	var src =url2query  + "/S3QL.php?format=json&key="+key+"&query=<S3QL><from>rules</from><where><project_id>"+project_id+"</project_id></where></S3QL>";
    s3db_jsonpp_call (src,'findRules("", ans, \'where\',\'where_attr_td\')');
   
    
}

  function array_push ( array ) {
    // Push one or more elements onto the end of array
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array_push/
    // +       version: 809.522
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_push(['kevin','van'], 'zonneveld');
    // *     returns 1: 3

    var i, argv = arguments, argc = argv.length;

    for (i=1; i < argc; i++){
        array[array.length++] = argv[i];
    }

    return array.length;
}

	function str_replace(search, replace, subject) {
		// Replace all occurrences of the search string with the replacement string
		// 
		// +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_str_replace/
		// +       version: 810.819
		// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +   improved by: Gabriel Paderni
		// +   improved by: Philip Peterson
		// +   improved by: Simon Willison (http://simonwillison.net)
		// +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
		// +   bugfixed by: Anton Ongson
		// +      input by: Onno Marsman
		// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +    tweaked by: Onno Marsman
		// *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
		// *     returns 1: 'Kevin.van.Zonneveld'
		// *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
		// *     returns 2: 'hemmo, mars'

		var f = search, r = replace, s = subject;
		var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;

		while (j = 0, i--) {
			if (s[i]) {
				while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
			}
		};

		return sa ? s : s[0];
	}

	function substr( f_string, f_start, f_length ) {
    // Return part of a string
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_substr/
    // +       version: 810.819
    // +     original by: Martijn Wieringa
    // +     bugfixed by: T.Wild
    // +      tweaked by: Onno Marsman
    // *       example 1: substr('abcdef', 0, -1);
    // *       returns 1: 'abcde'
    // *       example 2: substr(2, 0, -6);
    // *       returns 2: ''

    f_string += '';

    if(f_start < 0) {
        f_start += f_string.length;
    }

    if(f_length == undefined) {
        f_length = f_string.length;
    } else if(f_length < 0){
        f_length += f_string.length;
    } else {
        f_length += f_start;
    }

    if(f_length < f_start) {
        f_length = f_start;
    }

    return f_string.substring(f_start, f_length);
	
	}

	function in_array(needle, haystack, strict) {
    // Checks if a value exists in an array
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_in_array/
    // +       version: 809.522
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true

    var found = false, key, strict = !!strict;

    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }

    return found;
}

  function s3db_jsonpp_call (src,next_eval) {
     call = "call_"+Math.random().toString().replace(/\./g,"");//alert("787");
     var headID = document.getElementsByTagName("head")[0];
     var script = document.createElement('script');
     script.id = call;
     script.type = 'text/javascript';
     // using padded, parameterized JSON
     src=src+"&format=json&jsonp=s3db_jsonpp&jsonpp="+next_eval+"&onload=remove_element_by_id('"+script.id+"')";
     script.src = src ;//window.open(src);
     headID.appendChild(script); // retrieve answer
     document.getElementById(call).type = 'text/javascript';
	 }
 
	function remove_element_by_id (id) {
    var e = document.getElementById(id);
    e.parentNode.removeChild(e);
    return false}

	function s3db_jsonpp (ans,jsonpp) {
    eval(jsonpp);
    return ans;
	}

  function collectionDisplay(ans,parent_box) {
  	//if there is a brand new set of collections, replace the ones in the collection box with these ones
	document.getElementById('select_td').innerHTML ="";
	if(navigator.userAgent.match(/Chrome/)!=null || navigator.userAgent.match(/Safari/)!=null)
	   var selSize=2;
   else {
       selSize=1;
   }
   
   var newDiv=document.createElement('div');
   newDiv.id='collections';
   newDiv.collections = ans;
   document.body.appendChild(newDiv);
   document.collections = ans;
   var str  =  '<select size=5 id="select" OnClick="ruleConstrain(this.value, this.value+\'_rules\',\'where_attr_td\',1);removeChildNodes(\'value_box_td\',1,\'end\')" size="'+selSize+'">';
   //str +=  '<option value="*">*</option>';
   for (i = 0; i < ans.length; i++) {
      if(ans[i].name!='s3dbVerb'){
	  str += '<option value= "' + ans[i].collection_id + '" varName = "' +ans[i].name + '">' + ans[i].name + ' (C' + ans[i].collection_id + ')</option>';
	 }
   }

   str += '</select><input type="checkbox" id="all_tuples" unchecked/>All tuples';
   //append txt to this div

   document.getElementById('select_td').innerHTML = str;
   
   //at this point
   

   
}

function ruleDisplay(Cid, rules, sel_id,parent_id,replace) {
   
  
   //fill the rules box 
   if(replace)
	 {document.getElementById(parent_id).innerHTML = '';}	  //clear the parent node
   if(navigator.userAgent.match(/Chrome/)!=null || navigator.userAgent.match(/Safari/)!=null)
	   var selSize=2;
   else {
       selSize=1;
   }
   var str  =  '<select size=5 id="' +sel_id + '" onClick="navigate_ontology('+Cid+',document.getElementById(\''+sel_id+'\').childNodes, document.getElementById(\''+sel_id+'\').selectedIndex, \''+parent_id+'\');" size="'+selSize+'">';
  // str  += '<option value="all" style="font-style: italic" object="" object_id="C">(All attributes)</option>';
   var j=0;
   var rules_attr = [];
   for (i = 0; i < rules.length; i++) {
      if(rules[i].object!='UID'){
	  str += '<option subject="'+rules[i].subject+'" subject_id="'+rules[i].subject_id+'" rule_id="'+rules[i].rule_id +'" value= ":R' + rules[i].rule_id + '" class="C' +rules[i].subject_id + '" object="' +rules[i].object + '" object_id="C' +rules[i].object_id + '">R'+ rules[i].rule_id +': '+ rules[i].subject + ' - ' + rules[i].verb + ' - ' +rules[i].object +'</option>';
	  rules_attr[j] = rules[i];
	  j++;
	  }
   }
   str += '</select>';
   //append txt to this div
   
   
   var dataThere = document.getElementById(parent_id).innerHTML;
   if(dataThere!='undefined' && dataThere!='')	 {
   document.getElementById(parent_id).innerHTML = dataThere + str;

   }
   else {
       document.getElementById(parent_id).innerHTML = str;
   }
   document.getElementById(sel_id).rules = rules_attr;
   

}
 
 function findRules(Cid, ans, sel_id, parent_id) {
       document.getElementById('loading_collections').style.display = 'none';
	   document.getElementById('select_td').style.display = 'inline';
	   document.rules = ans;
	   var newDiv=document.createElement('div');
		newDiv.id='rules';
		newDiv.rules = ans;
		document.body.appendChild(newDiv);
		document.rules = new Array();
		for (i = 0; i < ans.length; i++) {
		  document.rules[ans[i].rule_id]  = ans[i];
		}
		ruleDisplay(Cid, ans, sel_id, parent_id);
		
  }
  
 function fillQueryText(option) {
	 
	 if(!url2query){
	 if(document.getElementById('uri_target'))
		 { 
			if(!document.getElementById('uri_target').value.match(/\.rdf/))
				url2query = document.getElementById('uri_target').value;
		 }
	 }
		 if(!url2query)
		 {
		   var url2query = 'http://ibl.mdanderson.org/TCGA/';
		   
		 }
		 
	 switch (option) {
	     case "0" :
			 var txt = '';
		 break;
		 
		 case "1" :
	        var txt = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \nPREFIX : <http://ibl.mdanderson.org/TCGA/>\nSELECT ?GenomicCharacterization ?RawData ?Type ?SampleID \nFROM <http://ibl.mdanderson.org/TCGA/>\nWHERE { \n ?GenomicCharacterization :R191 ?RawData .\n?GenomicCharacterization :R188 ?Platform .\n?Platform :R230 ?DataType .\n?DataType :R203 ?Type FILTER regex(?Type, "RNA") .\n?GenomicCharacterization :R3979 ?Sample .\nOPTIONAL { ?Sample :R12702 ?SampleID } . \n}';
			 //query using sparql.org 
			 document.getElementById('query_engine_s3ql').checked = true;		
			 break;
	     case "2" :
	        var txt = 	'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX : <http://ibl.mdanderson.org/TCGA/>\nSELECT ?patientID ?CancerType ?CollectionCenterName ?Experiment \n WHERE {\n	?Patient :R390 ?CancerType FILTER regex(?CancerType, "gbm") .\n	?Patient :R251 ?patientID .\n	?Patient :R47487 ?SampleCollectionCenter .\n	?SampleCollectionCenter :R44596 ?CollectionCenterName FILTER regex(?CollectionCenterName, "MD") .\n	?Sample :R247 ?Patient .\n	?Array :R3979 ?Sample .\n	?Array :R188 ?Platform .\n	?Array :R191 ?RawData .\n	?Platform :R230 ?DataType .\n	?DataType :R203 ?Experiment FILTER regex(?Experiment, "Copy Number") .\n\n }';
	        document.getElementById('query_engine_s3ql').checked = true;
			break;
		case "3" :
			var txt = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX : <http://ibl.mdanderson.org/TCGA/>\nSELECT ?PatientID ?Cancertype ?SampleCollectionCenter ?CGCCCenterID ?RawData \nWHERE {\n	?Patient :R47487 ?SCollCenter .\n	?Patient :R251 ?PatientID .\n	?Patient :R390 ?Cancertype .\n	?SCollCenter :R44596 ?SampleCollectionCenter FILTER regex(?SampleCollectionCenter, "MD Anderson") .\n	?Sample :R247 ?Patient .\n	?GenomicChar :R3979 ?Sample .\n	?GenomicChar :R191 ?RawData .\n\n }';
			document.getElementById('query_engine_s3ql').checked = true;
			break;
	    case "4" :
			//var txt = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX : <http://ibl.mdanderson.org/TCGA/>\nSELECT ?SampleID ?RawData ?TissueType\nFROM <'+url2query+'>\nWHERE {\n	?Sample :R247 ?ClinData .\n?ClinData :R11469 ?TissueType FILTER regex(?TissueType, "tumor") .\n?Sample :R12702 ?SampleID .\n	?Sample :R246 ?GenomicChar .\n?GenomicChar :R191 ?RawData .\n}';
			var txt = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX NCI: <http://rest.bioontology.org/bioportal/ontologies/download/39478#>\nPREFIX : <http://ibl.mdanderson.org/TCGA/>\nSELECT * \n FROM <http://ibl.mdanderson.org/TCGA/TCGA.rdf> \n WHERE {\n?MicroArrayCollection rdfs:isDefinedBy NCI:Technology_Platform .\n?MicroArray rdf:type ?MicroArrayCollection .\n?MicroArray rdfs:label ?MicroArrayName .\n}';
			document.getElementById('query_engine_s3ql').checked = true;
			break;
		case "5" :
			var txt = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX : <http://ibl.mdanderson.org/TCGA/>\nSELECT ?patientID ?SampleType ?RawData ?PlatformName\n WHERE {\n\n	?GenomicCharacterization :R191 ?RawData .\n	?GenomicCharacterization :R188 ?Platform . \n	?Platform :R149 ?PlatformName . \n	?GenomicCharacterization :R3979 ?Sample . \n	?Sample :R3746 ?SampleType . \n	?Sample :R247 ?Patient . \n	?Patient :R251 ?patientID FILTER regex(?patientID , "^TCGA-16-0850$") . \n\n }';
			document.getElementById('query_engine_s3ql').checked = true;
			break;
		
		case "6" :
			var txt = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX : <http://ibl.mdanderson.org/TCGA/>\nPREFIX s3db: <http://www.s3db.org/core#>\nSELECT ?rule ?Subject ?Predicate ?Object ?ObjectLabel\nFROM <'+url2query+'>\nWHERE\n{\n?rule a s3db:s3dbRule .\n?rule rdfs:subClassOf :P126 .\n?rule rdf:subject ?SubjectURI .\n?SubjectURI rdfs:label ?Subject .\n?rule rdf:predicate ?PredicateURI .\n?PredicateURI rdfs:label ?Predicate .\n?rule rdf:object ?Object .\nOPTIONAL { ?Object rdfs:label ?ObjectLabel . }\n}';
			document.getElementById('query_engine_s3ql').checked = true;
			break;
		
		case "7" :
			var txt = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX s3db: <http://www.s3db.org/core#>\nPREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX : <http://ibl.mdanderson.org/TCGA/>\nSELECT * \n WHERE {\n?Collection rdfs:subClassOf :P126 .\n?Collection rdf:type s3db:s3dbCollection .\n?Collection  rdfs:label ?CollectionLabel . \nOPTIONAL { ?Collection  rdfs:comment ?CollectionDesc .  }\n\n}';
			document.getElementById('query_engine_s3ql').checked = true;
		break;
		case "8" :
			var txt = 'PREFIX : <http://ibl.mdanderson.org/TCGA/>\nSELECT ?RawData\n WHERE {\n\n?GenomicCharacterization :R191 ?RawData . \n?GenomicCharacterization :R188 ?Platform . \n?Platform :R230 ?DataType . \n?DataType :R203 "Copy Number results" . \n\n?GenomicCharacterization :R53730 ?GenomicCharacterizationCenters . \n?GenomicCharacterizationCenters :R1275328 "mskcc.org" .\n\n?GenomicCharacterization :R3979 ?Sample . \n?Sample :R247 ?Patient . \n?Patient :R390 "gbm" . \n }';
			document.getElementById('query_engine_s3ql').checked = true;
		break;
		case "9" :
			var txt = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX genes: <http://www4.wiwiss.fu-berlin.de/diseasome/resource/genes/>\nPREFIX diseasome: <http://www4.wiwiss.fu-berlin.de/diseasome/resource/diseasome/>\nPREFIX : <http://ibl.mdanderson.org/TCGA/>\nSELECT ?AnalysisLabel ?geneSymbol ?geneProduct ?AssociatedDisease WHERE {\n    SERVICE <http://ibl.mdanderson.org/TCGA/sparql.php> {\n	?Analysis :R1057 ?AnalysisGenes . \n	?Analysis rdfs:label ?AnalysisLabel . \n	?AnalysisGenes :R1044 ?geneSymbol . \n	?AnalysisGenes :R1033 ?geneProduct .\n	}\n	?Genes rdfs:label ?geneSymbol .\n	?DiseaseID diseasome:associatedGene ?Genes .\n	?DiseaseID diseasome:name ?AssociatedDisease .\n}';
			document.getElementById('query_engine_store').checked = true;
		break;
		case "10" :
			var txt = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX : <http://ibl.mdanderson.org/TCGA/>\nSELECT ?PatientID ?Cancertype \nWHERE {\n	?Patient :R251 ?PatientID .\n	?Patient :R390 ?Cancertype FILTER regex(?Cancertype, "gbm") .\n}';
			document.getElementById('query_engine_s3ql').checked = true;
		break;
		case "11" :
			var txt = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX : <http://ibl.mdanderson.org/TCGA/>\nSELECT * \n WHERE {\n	?Sample :R3746 ?SampleType .\n	?Sample :R3746 "solid tumor" . \n	?Sample :R12702 ?SampleID . \n\n }';
			document.getElementById('query_engine_s3ql').checked = true;
		break;

		case "12" :
			var txt = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX NCI: <http://rest.bioontology.org/bioportal/ontologies/download/39478#>\nPREFIX mged: <http://mged.sourceforge.net/ontologies/MGEDOntology.owl#>\nPREFIX : <http://ibl.mdanderson.org/TCGA/>\nSELECT * \n WHERE {\n	?BioSourceClass rdfs:isDefinedBy mged:BioSource .\n	?BioSource rdf:type ?BioSourceClass .\n	?BioSource rdfs:label ?BioSourceLabel .\n}';
			document.getElementById('query_engine_s3ql').checked = true;
		break;
		case "13" : 
			var txt = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX NCI: <http://rest.bioontology.org/bioportal/ontologies/download/39478#>\nPREFIX mged: <http://mged.sourceforge.net/ontologies/MGEDOntology.owl#>\nPREFIX : <http://ibl.mdanderson.org/TCGA/>\nSELECT * \n WHERE {\n	?uid rdfs:isDefinedBy ?mapping .\n}';
		break;
		default: 
			var txt = '';
		break;
	 }
	 document.getElementById('query').value = txt;
     
 }

  function clearQuery() {
       
	   document.getElementById('query').innerHTML = '';
	   document.getElementById('query').value = '' ;
	   //location.reload(true);
 }

 function ruleConstrain(Cid, id_box,parent_box,replace) {
    document.getElementById('where_attr_td').style.display = 'inline';
	var allColl = document.getElementById("collections");
	
	if(Cid!='*')    {
	if(document.getElementById('rules'))
		{var Rules = document.getElementById("rules").rules;}
	else {
		var Rules = document.rules;
	}
	var ActiveRules = new Array();
	for (i = 0; i < Rules.length; i++) {
	 
		if(Rules[i].subject_id==Cid){ 
	 		array_push(ActiveRules, Rules[i]);
			
			//Rules[i].style.display = "none";
		}
		
	}
	
	//now re-write the rules for id-box
	document.subjects[Cid] = ActiveRules;
	ruleDisplay(Cid, ActiveRules, id_box,parent_box,replace)	
	
	}
	}
function changeFromToRDF() {
if(document.getElementById('uri_target'))
 { 
	if(document.getElementById('uri_target').value.match(/\.rdf/))
	 {url2query = document.getElementById('uri_target').value;
	  
	 }
	 

 }
 if(!url2query)
 {
   var url2query = 'http://ibl.mdanderson.org/TCGA/TCGA.rdf';  
    
 }
document.getElementById('uri_target').value = url2query;

//now change it on the query

newValue = document.getElementById('query').value.replace("FROM <http://ibl.mdanderson.org/TCGA/>", "FROM <http://ibl.mdanderson.org/TCGA/TCGA.rdf>");
document.getElementById('query').value = newValue;  

//hide the format span
document.getElementById('format_sel').setAttribute('style', 'display: none');
}

function changeFromToS3DB() {
if(document.getElementById('uri_target'))
 { 
	if(!document.getElementById('uri_target').value.match(/\.rdf/))
		url2query = document.getElementById('uri_target').value;
 }
 if(!url2query)
 {
   var url2query = 'http://ibl.mdanderson.org/TCGA/';  
 }
document.getElementById('uri_target').value = url2query;

//now change it on the query

newValue = document.getElementById('query').value.replace("FROM <http://ibl.mdanderson.org/TCGA/TCGA.rdf>", "FROM <http://ibl.mdanderson.org/TCGA/>");
document.getElementById('query').value = newValue;  

//display the format span
document.getElementById('format_sel').setAttribute('style', 'display: inline');
}


 function send_sparql() {
     
	 if(document.getElementById('query_engine_sparql').checked)
	 {
	  var sparqlEngine = "http://www.sparql.org/sparql?query="+encodeURIComponent(document.getElementById("query").value)+ '&default-graph-uri=&stylesheet=/xml-to-html.xsl';
	 }
	 
	 else if(document.getElementById('query_engine_store').checked) {
		var sparqlEngine = "http://ibl.mdanderson.org/~mhdeus/sparql_federation/sparql_query.php?query="+encodeURIComponent(document.getElementById("query").value);

	 }
	 else 
	 {     
		 var target = document.getElementById('s3db_deployment').value;
		 if(target)	{
			 
			 var sparqlEngine = target + "/sparql.php?query="+encodeURIComponent(document.getElementById("query").value);    
		 }
	 }
	 if(document.getElementById('format').value){
		 sparqlEngine += '&format='+document.getElementById('format').value;
	 }


	
	 //window.open(sparqlEngine, "sparql_result");
	 window.open(sparqlEngine);
 }
 
 

 
 
  

function queryAddTriple(sub, pred, obj) {
    if(!document.query) {document.query= new array();}
	if(!document.query.triple) {document.query.triple = new array();}
	if(!document.query.prefix) {document.query.prefix= new array();	}
	triple = str_replace(' ','',sub) + ' ' + pred + ' ' + obj + ' .';
	array_push(document.query.triple, triple);

}

function buildPattern() {
   
   
   //This is the collection in select
   // var Cid = str_replace(' ','',document.getElementById("select").childNodes[document.getElementById("select").selectedIndex].value);
   var Cid = document.getElementById('select').value;
   //This is the rule where the user has navigated into another collection (or not)
   var pogoRule = document.getElementById(Cid+'_rules').value;
   
   var or_checked = document.getElementById('or').checked;
   //triple for collection items
   var sub1 = '?'+str_replace(' ','',document.getElementById("select").childNodes[document.getElementById("select").selectedIndex].attributes["varName"].value);
   var pred1 ='rdf:type';
   var obj1	 = ':C' + Cid;
   
   //crete this triple onlly if pogorule has not been defined
	if(typeof(pogoRule)=='undefined' || pogoRule=='') {
		var triple = sub1 + ' ' +  pred1  + ' ' + obj1 + ' . ';

		//add this only if if does not exist
		var tmp = document.getElementById('query').value;
		if(or_checked){
			if(tmp.search('\n OPTIONAL { \\' + sub1 + ' rdfs:label \\' + sub1 + 'Label . } ')==-1)
				{
					triple += '\n OPTIONAL { ' + sub1 + ' rdfs:label ' + sub1 + 'Label . } ';
				}
		}
		else {
			if(tmp.search('\n \\' + sub1 + ' rdfs:label \\' + sub1 + 'Label . ')==-1){
				triple += '\n ' + sub1 + ' rdfs:label ' + sub1 + 'Label . ';
			}	
		}
	}
	else {
		var triple = '';
	}

    //triple += '\n OPTIONAL { ' + sub1 + ' rdfs:label ' + sub1 + 'Label } . ';
   //queryAddTriple(sub1, pred1, obj1)
  
   
   
	//Does pogoRule have a object_id
	var tripleOrder = new Array();
	

	
	while(pogoRule!=''){
		var currRule = document.rules[pogoRule.replace(/^:R/,'')];
		var tmp = new Array();
		var rule_id = currRule.rule_id;
		tmp.subject = '?'+str_replace(' ','',currRule.subject);
		tmp.predicate = ':R'+currRule.rule_id;
			//if(typeof currRule.object_id!='undefined')
			if(currRule.object_id!='')
			{
			tmp.object = '?'+str_replace(' ','',currRule.object);
			
			//now there is a new pogo rule
			pogoRule = document.getElementById(currRule.object_id+'_rules').value;
			}
		else {
			//is it not empty?
			if(document.getElementById('operators_' + rule_id)!=null)
			var op1 = document.getElementById('operators_'+rule_id).value;
			
			
			if(document.getElementById('attr_val_'+rule_id)!=null)
			var obj2 = 	document.getElementById('attr_val_'+rule_id).value;
			objVarName = '?'+str_replace(' ','',currRule.object);

			if(obj2){
				if(op1=='FILTER')
				{
				obj2 = objVarName + ' FILTER regex(' +objVarName+' , "' + obj2 + '", "i")';
				}
				else if(op1=='=')
				{
				obj2 = objVarName + ' FILTER regex(' +objVarName+' , "^' + obj2 + '$")';
				}
			var opt = false;
			tmp.object = obj2;
			}
			else {
			   tmp.object =  objVarName;
			   var opt = true;

			}
			pogoRule = '';
		}
		
		//triple += '\n' + tmp.subject + ' ' + tmp.predicate + ' ' + tmp.object + ' . ';
		if(opt && or_checked){
		triple += ' OPTIONAL { ' + tmp.subject + ' ' + tmp.predicate + ' ' + tmp.object + ' . } \n';
		}
		else {
		triple += tmp.subject + ' ' + tmp.predicate + ' ' + tmp.object + ' . \n';	
		}
		array_push(tripleOrder,rule_id);
		}
		
	
	
	 
	 if(document.query){
	 for (q = 0; q < document.query.triple.length; q++) {
	   triple += '\n' + document.query.triple[q];
	 }
	 }
	
	//if(document.getElementById('all_tuples').checked) {
	if(document.getElementById('all_tuples').checked || document.getElementById(Cid+'_rules').value=='all') {
	
	  // Need to find all the rule objects that shape this tuple
	  if(document.getElementById('select').value!='*')    {
		  var Rules = document.getElementById(Cid+'_rules').childNodes;
	  	  for (i = 0; i < Rules.length; i++) {
		   if (!Rules[i].disabled && !in_array(Rules[i].getAttribute('rule_id'), tripleOrder)) {
		       	var tmpObj = '?' + str_replace(' ','', Rules[i].attributes["object"].value);
				//triple += '\n OPTIONAL { ' + sub1 + ' ' + Rules[i].value + ' ' +  tmpObj + ' } .';
				if(or_checked){
				triple += '\n OPTIONAL { ' + sub1 + ' ' + Rules[i].value + ' ' +  tmpObj + ' } .';
				}
				else {
				triple += '\n ' + sub1 + ' ' + Rules[i].value + ' ' +  tmpObj + ' .';
				}
		   }
		  }
	  }
	 
	}
	
	//var query = document.getElementById('query').innerHTML;
	var query = document.getElementById('query').value;
	if(query){
	var tmp='';
	for (var i=0; i<(query.length-1); i++) {
		tmp  += query[i];
	}
	var query = tmp+'\n'+triple+'\n }';

	
	//	var p=str_replace(/WHERE(.|\n)*/.exec(query),'',query);
	//	var q=/(.|\n*)WHERE\s*{(.|\n*)*}/.exec(query,'i');
	//	var r=str_replace("\n",'',q[0]);
	//	t = /WHERE\s*{(.*)}/.exec(r);
	//	t=t[1] + '\n' + '\t' + triple;
	//	 query = p + '\nWHERE \n{' + t + '\n}';
	
	}
	else {
	    if(document.getElementById('s3db_deployment').value) {var prefURL = document.getElementById('s3db_deployment').value;}
		var prefix = 'PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX : <http://ibl.mdanderson.org/TCGA/>';
		//var query =   prefix  + '\n' + 'SELECT * \n FROM <'+document.getElementById('s3db_deployment').value +'> \n WHERE {\n' + triple + '\n}';
		var query =   prefix  + '\n' + 'SELECT * \n WHERE {\n' + triple + '\n}';
		
	}
	 document.getElementById('query').value = query;

  
}

function navigate_ontology(Cid, Rules, ind,parent_id) {
	
	
	//now clean the div and create it again
	if(!document.getElementById(Cid+'_value_box'))
	{
	var varBox = document.createElement('span');
	varBox.id = Cid+'_value_box';
	//append to parent id
	document.getElementById(parent_id).appendChild(varBox);
	}
	else {
	    varBox = document.getElementById(Cid+'_value_box');
		varBox.innerHTML = '';
	}
	//Find out which index is selected:
	var ind = document.getElementById(Cid+'_rules').selectedIndex;

	//Retrieve information on that rule
	var rule_info = Rules[ind];
	
	
	 if(rule_info.attributes['object_id'].value=='C' || rule_info.attributes['object_id'].value=='' || rule_info.attributes['object_id'].value=='Cundefined')
	{ 
	  
	  document.navigation = rule_info.attributes['rule_id'].value;
	  newSpan = document.createElement('span');
	  //newSpan.class="operator";
	  newSpan.id = "operator_"+substr(rule_info.value,2,rule_info.value.length);
	  varBox.appendChild(newSpan);
	 
	display_input_box(rule_info.attributes['rule_id'].value,newSpan.id);
	
	}
	else {
	  
	  var divTxtBox = document.createElement('div');
	  divTxtBox.id = rule_info.attributes['rule_id'].value+'_value';
	  divTxtBox.innerHTML = '';
		
	  //Append the new div to parentid element
	  varBox.appendChild(divTxtBox);
		
		var objToMatch = rule_info.attributes['object_id'].value.replace(/^C/,'');
	  
	  
	  //Now retrieve the rules where the indicared object ID is treated as subject.
	  var thisTd = document.getElementById('value_box_td');
	  var newDiv = document.createElement('div');
	  newDiv.id = objToMatch+'_nav';
	  newDiv.collection_id =  objToMatch;
	  thisTd.appendChild(newDiv);
	  var replace=1;
	  ruleConstrain(objToMatch, objToMatch+'_rules',newDiv.id,replace);
	  //Keep running it until we run out of collections
	  //Find all the childNodes of rules that have this object_id as their subject
	 
	 //alert("You have chosen a rule that point to another collection. I am still developing this feature. Come back soon and your wishes will come true :-).");
	// build_new_ruleSet(rule_info, "query_builder_table");
	
  	 
	
	}
}

function  display_input_box(rule_id, parent_id) {
     //Ok, so this is a literal object - display the regualr text box
	
	var op_sel = '<select id="operators_'+rule_id+'"><option value="FILTER">~</option><option>=</option></select>';//<option>></option><option><</option> soon...
   
	document.getElementById(parent_id).innerHTML = op_sel + '<input type="text" id="attr_val_'+rule_id+'"><span style="font-size: 14">Click and point <a id="tooltip" href="javascript:showRuleVals('+rule_id+')" onMouseOut="UnTip()" onBlur="UnTip()"><U>here</U></a> to view queriable values</span>';
	//document.getElementById(parent_id).innerHTML = op_sel + '<input type="text" id="attr_val_'+rule_id+'"><span style="font-size: 10">Chose more values by chosing another collection</span>';
	//document.getElementById('where_value_td').innerHTML ='<input type="text" id="attr_val">';
}

function  build_new_ruleSet(rule_info, parent_id) {
     
	 	  
	  next_subject_id = substr(rule_info.attributes['object_id'].value, 1,rule_info.attributes['object_id'].value.length)
	  
	  //now choose the options;
	  var allRules = document.getElementById('rules').rules;
	  var activeRules = new Array();
	  for (i = 0; i < allRules.length; i++) {
	      if(allRules[i].subject_id == next_subject_id)	 {
				array_push(activeRules, allRules[i]);
		  }
		  if(allRules[i].rule_id == substr(rule_info.value, 2, rule_info.value.length)	  )
		  {
		  rule= allRules[i];
		  }
	  }
	  document.navigation = rule['rule_id'];
	  newTr = document.createElement('tr');
	  //newTr.class = "rules_box";
	  newTd_a = document.createElement('td');
	  newTr.appendChild(newTd_a);
	  newTd = document.createElement('td');
	  newTd.id ='where_'+rule['rule_id']; 
	  newTr.appendChild(newTd);
	  document.getElementById(parent_id).appendChild(newTr);
	  
	  //This means also a new triple for the query
	  queryAddTriple('?'+rule['subject'], ':R'+rule['rule_id'], '?'+str_replace(' ','',rule['object']));
	  ruleDisplay(next_subject_id, activeRules, "rules_box_"+rule['subject_id'],'where_'+rule['rule_id'], 0);
	  

	}
function when_enter_call_api_login(event) {
	
	if(event.keyCode==13 || event.keyCode==9|| event=='go'){
		
		var url = document.getElementById('s3db_deployment').value;
		var uname = document.getElementById('username');
		var pass = document.getElementById('password');
		var authority = document.getElementById('authority').value;
		if(uname){username=uname.value;}
		if(pass){password=pass.value;}

		url += '/apilogin.php?username='+username+'&password='+password+'&authority='+authority;
		
		
		s3db_jsonpp_call (url,"get_key(ans)");

	}
}

function get_key(ans) {
	
	if(ans[0].key_id){
		document.getElementById('key').value=ans[0].key_id;
	}
	get_projects();

}

function when_enter_grab_public_projects(event) {
	if(event.keyCode==13){
		get_projects();
		
	}
}

function removeChildNodes(divname, start, endi) {
	if(endi=='end') {var endi = document.getElementById(divname).childNodes.length;	}
	var i=start;
	var toRemoveCount=endi-start;
	var j=0;
	while (j<(toRemoveCount)) {//this is necessary becuse each time i delete a node, the length decreases by 1
		 document.getElementById(divname).removeChild(document.getElementById(divname).childNodes[i]);
		 j++;
	}
	
}

function toggle_links(toggle_id, toHide_id) {
	if(document.getElementById(toggle_id).innerHTML=='(hide)'){
		document.getElementById(toggle_id).innerHTML='(show)';
		document.getElementById(toHide_id).style.display='none'
	}
	else {
		document.getElementById(toggle_id).innerHTML='(hide)';
		document.getElementById(toHide_id).style.display='inline'
	}
}

function showRuleVals(rule_id) {
	//start by showing the loading
	
	if(!navigator.userAgent.match(/Chrome/)){
	Tip('<img src="loading.gif">');
	}
	if(document.getElementById('key')) { var key = document.getElementById('key').value; }
	else {
		var key = "";
	}
	var s3ql = url2query+"S3QL.php?key="+key+"&query=<S3QL><select>value</select><from>statement</from><where><rule_id>"+rule_id+"</rule_id></where></S3QL>";
	document.s3ql = s3ql;
	//window.open(s3ql, "ruleValues", "status=1,location=1,resizable=1,width=350,height=250");
	s3db_jsonpp_call (s3ql,"showRuleValuesTip(ans)");
}
function showRuleValuesTip(ans) {
	if(!navigator.userAgent.match(/Chrome/) && !navigator.userAgent.match(/Safari/)){
	UnTip();
	}
	if(ans){
		var data = [];
		var displayData = "";

		for (var i in ans) {
			data[i] = ans[i].value;
		}	
		var dData = unique(data);
		dData.sort();
		for (var i=0; i<dData.length; i++) {
			displayData += dData[i];
			if(i!=dData.length){
				displayData += "</br>";
			}
		}
		if(!navigator.userAgent.match(/Chrome/) && !navigator.userAgent.match(/Safari/)){
		Tip(displayData);
		}
		else {
			//window.open(document.s3ql);
		   document.getElementById("tooltip").title =  displayData;
		}
	}
	else {
		Tip("No queriable values for this rule");
	}
}

function unique(data) {
	var r = new Array();
	o:for(var i = 0, n = data.length; i < n; i++)
	{
		for(var x = 0, y = r.length; x < y; x++)
		{
			if(r[x]==data[i])
			{
				continue o;
			}
		}
		r[r.length] = data[i];
	}
	return r;
}